#include "Texture2D.h"

using namespace EPOC;
Texture2D::Texture2D()
{
	SetClassID(kCLASSID_TEXTURE_OGL);
	texture = 0;
}



Texture2D::~Texture2D()
{
}

void Texture2D::Cleanup()
{
	if(texture > 0)
		glDeleteTextures( 1, &texture );
}

bool Texture2D::Initialize(const char* sName, const char* sFilePath, SDL_Surface *pSDLSurface, bool bExclusive, bool bEditable)
{
	/*if(Texture::Initialize(sName, sFilePath, bExclusive) == false)
		return false;*/

	//if(!pSDLSurface)
	//	return false;

	name = sName;

	editable = bEditable;
	texture = BuildGLTexture(pSDLSurface, !IsEditable());
	
	if( IsEditable() )
		SDLSurface = pSDLSurface;

	return true;
}

bool Texture2D::UpdateTexture()
{
	return RebuildGLTexture();
}

GLuint Texture2D::BuildGLTexture(SDL_Surface *pSDLSurface, bool bRemove)
{
	if(!pSDLSurface)
		return 0;

	if(texture == 0)
		glGenTextures( 1, &texture );		// Have OpenGL generate a texture object handle for us

	// Bind the texture object
	glBindTexture( GL_TEXTURE_2D, texture );
 
	// Set the texture's stretching properties
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

	if( SDL_MUSTLOCK( pSDLSurface))
		if( SDL_LockSurface( pSDLSurface) > 0 )
			return 0;

			// Edit the texture object's image data using the information SDL_Surface gives us
			glTexImage2D( GL_TEXTURE_2D, 0, pSDLSurface->format->BytesPerPixel, pSDLSurface->w, pSDLSurface->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, pSDLSurface->pixels );
		
	if( SDL_MUSTLOCK( pSDLSurface))
		SDL_UnlockSurface( pSDLSurface );

	//SetDimension(pSDLSurface->h, pSDLSurface->w);
	
	if(bRemove)
		SDL_FreeSurface(pSDLSurface);

	return texture;
}

bool Texture2D::RebuildGLTexture()
{
	if(texture == 0)
		return false;

	/*if(!GetSDLSurface())
		return false;
*/
	glBindTexture( GL_TEXTURE_2D, texture );
 
	// Set the texture's stretching properties
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

	if( SDL_MUSTLOCK( SDLSurface))
		if( SDL_LockSurface( SDLSurface) > 0 )
			return false;

	// Edit the texture object's image data using the information SDL_Surface gives us
	glTexImage2D( GL_TEXTURE_2D, 0, SDLSurface->format->BytesPerPixel, SDLSurface->w, SDLSurface->h, 0, GL_BGRA, GL_UNSIGNED_BYTE,  SDLSurface->pixels );

	if( SDL_MUSTLOCK( SDLSurface ) )
		SDL_UnlockSurface( SDLSurface );

	//SetDimension(GetSDLSurface()->h, GetSDLSurface()->w);

	return true;
}